package photogcalc.calculators;

import photogcalc.calc.DepthOfField;
import photogcalc.util.Formatter;
import photogcalc.util.Settings;
import javax.microedition.lcdui.Screen;
import net.sf.microlog.core.Logger;
import net.sf.microlog.core.LoggerFactory;
import photogcalc.ChildFormListener;
import photogcalc.common.FrameSize;

/**
 *
 * @author aokkonen
 */
public class DofController extends CalculatorController implements DofCommandListener {
    private DofView view = null;
    private DofModel model = null;

    Logger logger = LoggerFactory.getLogger("DofController");

    public DofController(ChildFormListener listener, Settings settings) {
        super(listener);

        model = new DofModel(settings);
        view = new DofView(settings, this);

        view.initData(model.getCameraFormats(), model.getFstops(), model.getFlengths());
    }

    public void calculateCommand() {
        logger.debug("calculateCommand");
        calculateDof();
    }

    private void calculateDof() {
        // Calculate depth of field.
        //Double coc = (Double) model.getCoCs().get(model.getSettings().get("cameraformat"));
        FrameSize frameSize = (FrameSize)model.getFrameSizes().get(model.getSettings().get("cameraformat"));
        Double coc = new Double(frameSize.getCoC());
        DepthOfField dof = new DepthOfField(coc.doubleValue());

        dof.calculate(
            Double.parseDouble(model.getSettings().get("focallength")),
            Double.parseDouble(model.getSettings().get("aperture")),
            /* convert meters to millimeters */
            Double.parseDouble(model.getSettings().get("distance")) * 1000.0
        );

        boolean isInf = false;
        if (dof.getFarDistance() < 0) {
            isInf = true;
        }

        view.setFront(Formatter.format(dof.getNearDistance() / 1000, 2)+"m");
        if (isInf) {
            view.setBackInf();
        } else {
            view.setBack(Formatter.format(dof.getFarDistance() / 1000, 2)+"m");
        }
        view.setHyperfocal(Formatter.format(dof.getHyperfocalDistance() / 1000, 2)+"m");

        dof = null;
    }

    public String getIconPrefix() {
        return DofView.ICONPREFIX;
    }
    
    public String getMenuName() {
        return DofView.MENUNAME;
    }

    public void refreshScreen() {
        view.refresh();
    }
    
    public Screen getScreen() {
        return view.getScreen();
    }
}
